﻿
package kliment.display.filters.noise {
	import flash.display.MovieClip;
	import flash.geom.Point;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.filters.DisplacementMapFilter;
	import flash.filters.DisplacementMapFilterMode;
	import flash.filters.ConvolutionFilter;
	import flash.filters.BlurFilter;
	import flash.filters.BitmapFilterQuality;

	/**
	* ...
	* @author Kliment
	*/
	public dynamic class NoiseMatrix extends Array{
		private var _bitmap:Bitmap;
		
		public static const MAX:int = 100;
		public static const MIN:int = 0;
		
		private const NUM_OCTAVES:int = 5;
		
		public function NoiseMatrix(bitmap:Bitmap) {
			_bitmap = bitmap;
		}
		
		public function glass(value:Number):void {
			value = cleanValue(value, MAX);
			if (value > 0){
				var size:Number = Math.min(_bitmap.width, _bitmap.height)/MAX * value / Math.PI;
				var scale:Number = value/100*50+(MAX/100*10);
				var bitmapData:BitmapData = new BitmapData(_bitmap.width, _bitmap.height);
				var pointsArray:Array = [	new Point( -size, size / 2),
											new Point(size / 2, -size),
											new Point(size, size),
											new Point(size, 0),
											new Point(0, -size)];
											
				bitmapData.perlinNoise(size, size, NUM_OCTAVES, .5, true, true, 1, true, pointsArray);
				
				this.push(new DisplacementMapFilter(bitmapData, new Point(0, 0), 1, 1, scale, scale, DisplacementMapFilterMode.CLAMP, 0, 0));
			}
		}
		
		public function popArt(value:Number):void {
			value = cleanValue(value, MAX);
			
			var temp:MovieClip = new MovieClip();
			temp.x = 350; temp.y = 60;
			//temp.addChild(new PopArt(_bitmap,value));
			///_bitmap.parent.addChild(temp);
			
			/*var bitmapData:BitmapData = new BitmapData(_bitmap.width, _bitmap.height);
			
			bitmapData.perlinNoise(4, 4, NUM_OCTAVES, .5, true, true, 1, true);
			
			this.push(new DisplacementMapFilter(bitmapData, new Point(0, 0), 1, 1, 3, 3, DisplacementMapFilterMode.CLAMP, 0, 0));*/
		}
		
		public function edges(value:Boolean):void {
			if (value) {
				var matrix:Array = [0, 1, 0,
									1, -3, 1,
									0, 1, 0];
				this.push(new ConvolutionFilter(3, 3, matrix, 0))
			}
		}
		
		public function blur(value:Number):void {
			value = cleanValue(value, MAX);
			if (value > 0)
				this.push(new BlurFilter(value, value, BitmapFilterQuality.HIGH));
		}
		
		private function cleanValue(value:Number,limit:Number):Number {
			return Math.min(limit, Math.max(MIN, value));
		}
	}
	
}
